﻿using System;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.SessionState;
using System.Diagnostics;
using System.Reflection;

namespace WebApp
{
    public class AppEngine:IHttpModule
    {
        
        private string Siteroot;
        private Hashtable Objects;

        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            //throw new NotImplementedException();
            Siteroot = ConfigurationManager.AppSettings["SiteRoot"];
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);
            Objects = ObjectCache.Cache().Data;
            LoadObject();
        }

        void context_EndRequest(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            if (ThreadBaseData.Get().Data.ContainsKey(Thread.CurrentThread.ManagedThreadId))
            {
                ThreadBaseData.Get().Data.Remove(Thread.CurrentThread.ManagedThreadId);
            }
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            if (ThreadBaseData.Get().Data.ContainsKey(Thread.CurrentThread.ManagedThreadId))
            {
                ThreadBaseData.Get().Data[Thread.CurrentThread.ManagedThreadId] = new Hashtable();
            }
            else
            {
                ThreadBaseData.Get().Data.Add(Thread.CurrentThread.ManagedThreadId, new Hashtable());
            }
        }
        void LoadObject()
        {
            string tpname = string.Empty;
            System.Reflection.Assembly[] assls = AppDomain.CurrentDomain.GetAssemblies();
            foreach (System.Reflection.Assembly ass in assls)
            {
                Type[] tps = ass.GetTypes();
                foreach (Type tp in tps)
                {
                    if (tp.BaseType != null)
                    {
                        tpname = tp.Name.ToLower();
                        if (tp.BaseType.Equals(typeof(ControllerBase)))
                        {
                            if (!Objects.ContainsKey(tpname))
                            {
                                Objects.Add(tpname, Activator.CreateInstance(tp));
                            }
                        }
                    }
                }
            }
        }
    }
}
